import { constantRoutes } from '@/router';
import { getRouters } from '@/api/menu';
import Layout from '@/layout/index.vue';
import ParentView from '@/components/ParentView';
import { toCamelCase } from '@/utils';
// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue');

let parentId = 0;
const permission = {
  state: {
    routes: [],
    addRoutes: [],
    sidebarRouters: [],
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes;
      state.routes = constantRoutes.concat(routes);
    },
    SET_SIDEBAR_ROUTERS: (state, routers) => {
      state.sidebarRouters = constantRoutes.concat(routers);
    },
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise((resolve) => {
        const params = {
          type: 8, // 8代表护士长手册系统
        };
        // 向后端请求路由数据
        getRouters(params).then((res) => {
          parentId = res.data[0].id;
          const routes = res.data[0]?.children.map((i) => ({
            ...i,
            path: i.path.startsWith('/') ? i.path : `/${i.path}`,
          }));
          const sdata = JSON.parse(JSON.stringify(routes));
          const rdata = JSON.parse(JSON.stringify(routes));

          const sidebarRoutes = filterAsyncRouter(sdata || []);
          let rewriteRoutes = filterAsyncRouter(rdata || [], false, true);
          console.log('sidebarRoutes', sidebarRoutes);
          console.log('rewriteRoutes', rewriteRoutes);

          // 合并一级菜单的路由
          rewriteRoutes = mergeFirstMenu(rewriteRoutes);

          rewriteRoutes.push({ path: '/:pathMatch(.*)*', redirect: '/404', hidden: true });
          // console.log('rewriteRoutes', rewriteRoutes)
          commit('SET_ROUTES', rewriteRoutes);
          commit('SET_SIDEBAR_ROUTERS', sidebarRoutes);
          resolve(rewriteRoutes);
        });
      });
    },
  },
};

function mergeFirstMenu(routeArr) {
  const newRoutes = [];
  let firstRoutes = null;
  routeArr.forEach((route) => {
    if (route.path === '/first') {
      if (firstRoutes) {
        firstRoutes.children.push(route.children[0]);
      } else {
        firstRoutes = route;
      }
    } else {
      newRoutes.push(route);
    }
  });
  firstRoutes && newRoutes.push(firstRoutes);
  return newRoutes;
}
const menuIconMap = {
  workPlane: 'icon-icon-shaixuan',
  objectives: 'icon-caidan-gongzuomubiao',
  workSummary: 'icon-caidan-gongzuozongjie',
  meet: 'icon-caidan-huiyijilu',
  notepad: 'icon-caidan-jishiben',
};
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter((route) => {
    // 将 ruoyi 后端原有耦合前端的逻辑，迁移到此处
    // 处理 meta 属性
    route.meta = {
      title: route.name,
      icon: route.icon,
      noCache: !route.keepAlive,
      id: route.id,
      visible: route.visible,
      fontIcon: menuIconMap[route.path] || undefined,
    };
    // 路由地址转首字母大写驼峰，作为路由名称，适配 keepAlive
    route.name = toCamelCase(route.path, true);
    // 处理三级及以上菜单路由缓存问题，将path名字赋值给name
    if (route.path.includes('/')) {
      const pathArr = route.path.split('/');
      route.name = toCamelCase(pathArr[pathArr.length - 1], true);
    }

    route.hidden = !route.visible;
    // 处理 component 属性
    if (route.children) {
      // 父节点
      if (route.parentId === parentId) {
        route.component = Layout;
      } else {
        route.component = ParentView;
      }
    } else {
      // 根节点
      route.component = loadView(route.component);
    }

    // filterChildren
    if (type && route.children) {
      route.children = filterChildren(route.children);
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type);
    } else {
      delete route['children'];
    }
    return true;
  });
}

function filterChildren(childrenMap, lastRouter = false) {
  let children = [];
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (!el.component && !lastRouter) {
        el.children.forEach((c) => {
          c.path = `${el.path}/${c.path}`;
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c));
            return;
          }
          children.push(c);
        });
        return;
      }
    }
    if (lastRouter) {
      el.path = `${lastRouter.path}/${el.path}`;
    }
    children = children.concat(el);
  });
  return children;
}

export function loadView(view) {
  let res;
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0];
    if (dir === view) {
      res = () => modules[path]();
    }
  }
  return res;
}

export default permission;
